"""
权限系统API路由
提供角色、权限、用户角色关联等API接口
"""
from typing import List, Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel import Session

from common.utils import SessionDep
from app.users.models import User, Role, Permission, UserRole, RolePermission
from app.users.schema import (
    RoleCreate, RoleUpdate, RoleResponse,
    PermissionCreate, PermissionUpdate, PermissionResponse,
    UserRoleCreate, UserRoleResponse,
    RolePermissionCreate, RolePermissionResponse,
    UserPermissionsResponse, RolePermissionsResponse
)
from app.users.permission_help import (
    create_role, get_role_by_id, get_role_by_code, get_all_roles, update_role, delete_role,
    create_permission, get_permission_by_id, get_permission_by_code, get_all_permissions, 
    update_permission, delete_permission,
    assign_role_to_user, remove_role_from_user, get_user_roles,
    assign_permission_to_role, remove_permission_from_role, get_role_permissions,
    get_user_permissions, check_user_permission, check_user_resource_permission
)

router = APIRouter()


# ==================== 角色管理API ====================

@router.post("/roles", response_model=RoleResponse, status_code=status.HTTP_201_CREATED)
def create_role_api(session: SessionDep, role_data: RoleCreate):
    """创建角色"""
    # 检查角色代码是否已存在
    existing_role = get_role_by_code(session, role_data.code)
    if existing_role:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="角色代码已存在"
        )
    
    return create_role(session, role_data)


@router.get("/roles", response_model=List[RoleResponse])
def get_roles_api(session: SessionDep, skip: int = 0, limit: int = 100):
    """获取所有角色"""
    return get_all_roles(session, skip, limit)


@router.get("/roles/{role_id}", response_model=RoleResponse)
def get_role_api(session: SessionDep, role_id: int):
    """根据ID获取角色"""
    role = get_role_by_id(session, role_id)
    if not role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    return role


@router.put("/roles/{role_id}", response_model=RoleResponse)
def update_role_api(session: SessionDep, role_id: int, role_data: RoleUpdate):
    """更新角色"""
    role = update_role(session, role_id, role_data)
    if not role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    return role


@router.delete("/roles/{role_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_role_api(session: SessionDep, role_id: int):
    """删除角色"""
    success = delete_role(session, role_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )


# ==================== 权限管理API ====================

@router.post("/permissions", response_model=PermissionResponse, status_code=status.HTTP_201_CREATED)
def create_permission_api(session: SessionDep, permission_data: PermissionCreate):
    """创建权限"""
    # 检查权限代码是否已存在
    existing_permission = get_permission_by_code(session, permission_data.code)
    if existing_permission:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="权限代码已存在"
        )
    
    return create_permission(session, permission_data)


@router.get("/permissions", response_model=List[PermissionResponse])
def get_permissions_api(session: SessionDep, skip: int = 0, limit: int = 100):
    """获取所有权限"""
    return get_all_permissions(session, skip, limit)


@router.get("/permissions/{permission_id}", response_model=PermissionResponse)
def get_permission_api(session: SessionDep, permission_id: int):
    """根据ID获取权限"""
    permission = get_permission_by_id(session, permission_id)
    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="权限不存在"
        )
    return permission


@router.put("/permissions/{permission_id}", response_model=PermissionResponse)
def update_permission_api(session: SessionDep, permission_id: int, permission_data: PermissionUpdate):
    """更新权限"""
    permission = update_permission(session, permission_id, permission_data)
    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="权限不存在"
        )
    return permission


@router.delete("/permissions/{permission_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_permission_api(session: SessionDep, permission_id: int):
    """删除权限"""
    success = delete_permission(session, permission_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="权限不存在"
        )


# ==================== 用户角色管理API ====================

@router.post("/users/{user_id}/roles", response_model=UserRoleResponse, status_code=status.HTTP_201_CREATED)
def assign_role_to_user_api(session: SessionDep, user_id: int, role_id: int):
    """为用户分配角色"""
    # 检查用户是否存在
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 检查角色是否存在
    role = get_role_by_id(session, role_id)
    if not role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    
    return assign_role_to_user(session, user_id, role_id)


@router.delete("/users/{user_id}/roles/{role_id}", status_code=status.HTTP_204_NO_CONTENT)
def remove_role_from_user_api(session: SessionDep, user_id: int, role_id: int):
    """移除用户的角色"""
    success = remove_role_from_user(session, user_id, role_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户角色关联不存在"
        )


@router.get("/users/{user_id}/roles", response_model=List[RoleResponse])
def get_user_roles_api(session: SessionDep, user_id: int):
    """获取用户的所有角色"""
    # 检查用户是否存在
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return get_user_roles(session, user_id)


@router.get("/users/{user_id}/permissions", response_model=UserPermissionsResponse)
def get_user_permissions_api(session: SessionDep, user_id: int):
    """获取用户的所有权限"""
    # 检查用户是否存在
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    roles = get_user_roles(session, user_id)
    permissions = get_user_permissions(session, user_id)
    
    return UserPermissionsResponse(
        user_id=user_id,
        roles=roles,
        permissions=permissions
    )


# ==================== 角色权限管理API ====================

@router.post("/roles/{role_id}/permissions", response_model=RolePermissionResponse, status_code=status.HTTP_201_CREATED)
def assign_permission_to_role_api(session: SessionDep, role_id: int, permission_id: int):
    """为角色分配权限"""
    # 检查角色是否存在
    role = get_role_by_id(session, role_id)
    if not role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    
    # 检查权限是否存在
    permission = get_permission_by_id(session, permission_id)
    if not permission:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="权限不存在"
        )
    
    return assign_permission_to_role(session, role_id, permission_id)


@router.delete("/roles/{role_id}/permissions/{permission_id}", status_code=status.HTTP_204_NO_CONTENT)
def remove_permission_from_role_api(session: SessionDep, role_id: int, permission_id: int):
    """移除角色的权限"""
    success = remove_permission_from_role(session, role_id, permission_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色权限关联不存在"
        )


@router.get("/roles/{role_id}/permissions", response_model=RolePermissionsResponse)
def get_role_permissions_api(session: SessionDep, role_id: int):
    """获取角色的所有权限"""
    # 检查角色是否存在
    role = get_role_by_id(session, role_id)
    if not role:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="角色不存在"
        )
    
    permissions = get_role_permissions(session, role_id)
    
    return RolePermissionsResponse(
        role_id=role_id,
        role=role,
        permissions=permissions
    )


# ==================== 权限检查API ====================

@router.get("/check/{user_id}/{permission_code}")
def check_user_permission_api(session: SessionDep, user_id: int, permission_code: str):
    """检查用户是否拥有指定权限"""
    # 检查用户是否存在
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    has_permission = check_user_permission(session, user_id, permission_code)
    return {"has_permission": has_permission}


@router.get("/check/{user_id}/{resource}/{action}")
def check_user_resource_permission_api(session: SessionDep, user_id: int, resource: str, action: str):
    """检查用户是否对指定资源有指定操作的权限"""
    # 检查用户是否存在
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    has_permission = check_user_resource_permission(session, user_id, resource, action)
    return {"has_permission": has_permission}
